package com.jianguozh.difs.support.service.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jianguozh.difs.framework.model.LoginInfo;
import com.jianguozh.difs.support.service.event.LoginSucceedEvent;
import com.jianguozh.difs.support.service.sys.entity.User;
import com.jianguozh.difs.support.service.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录成功事件监听
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/6/20 10:24
 */
@Component
public class LoginSucceedListener {

    @Autowired
    IUserService userService;

    @Async
    @Order
    @EventListener(LoginSucceedEvent.class)
    public void saveLog(LoginSucceedEvent event) {
        LoginInfo loginInfo = (LoginInfo) event.getSource();
        String username = loginInfo.getUsername();
        User user = userService.getByUsername(username);
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(User::getLastLoginTime, user.getCurrLoginTime());
        updateWrapper.set(User::getLastLoginIp, user.getCurrLoginIp());
        updateWrapper.set(User::getCurrLoginIp, loginInfo.getLoginIp());
        updateWrapper.set(User::getCurrLoginTime, LocalDateTime.now());
        updateWrapper.eq(User::getId, user.getId());
        userService.update(updateWrapper);
    }
}
